//
//  NetTools.m
//  CareRing
//
//  Created  on 2025/3/19.
//
    

#import "NetTools.h"
#import <CommonCrypto/CommonCrypto.h>

@implementation NetTools
+(NSString *)URLEncodeString:(NSString *)string
{
    NSString * encodestring = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string,NULL,(CFStringRef)@"!*'();:@&=+$,/?%#[]",kCFStringEncodingUTF8));
  
    
    NSMutableString * outputStr = [NSMutableString stringWithString:encodestring];
    [outputStr replaceOccurrencesOfString:@"%20" withString:@"+" options:NSLiteralSearch range:NSMakeRange(0, [outputStr length])];
    return outputStr;
}

+(NSString *)signStringWith:(NSString *)sn MacAddr:(NSString *)mac Secret:(NSString *)secret
{
    if (!sn.length || !mac.length || !secret.length) {
        return nil;
    }
    
    NSString *sign = [self hmacMD5WithKey:secret data:[NSString stringWithFormat:@"%@,%@", sn, mac]];
    return sign;
}


+ (NSString *)hmacMD5WithKey:(NSString *)key data:(NSString *)data {
    // 将 key 和 data 转换为 C 字符串
    const char *cKey = [key cStringUsingEncoding:NSUTF8StringEncoding];
    const char *cData = [data cStringUsingEncoding:NSUTF8StringEncoding];
    
    // 定义 HMAC 结果数组
    unsigned char cHMAC[CC_MD5_DIGEST_LENGTH];
    
    // 计算 HMAC-MD5
    CCHmac(kCCHmacAlgMD5, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    
    // 将结果转换为十六进制字符串
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02x", cHMAC[i]];
    }
    
    return result;
}

@end
